package models

import (
	"hello/wl"
)

type Post struct {
	Id          int
	Title       string
	Content     string
	UserId     int
	Isok        string
	BaseMode
	//User   User `gorm:"ForeignKey:Id;AssociationForeignKey:User_id"`
}


//首页文章的结构
type PostUser struct {
	Post
	Username string
	Zcount string
	Ccount string
}

//文章展示的结构
type PostShow struct {
	Post
	Username string
}

//设置Post表名
func (u *Post) TableName() string {
	return "post"
}

//所有文章分页查询,以及count
func (this *PostUser)PostSelect(limit int,page int) ([]PostUser,int) {
	var postUserList []PostUser
	var count int

	wl.DB.Table("post").Count(&count)

	wl.DB.Table("post").Select("post.*,user.username," +
		"(SELECT COUNT(1) FROM zan WHERE zan.`post_id`=post.id) AS zcount," +
		"(SELECT COUNT(1) FROM `comment` WHERE comment.`post_id`=post.id) AS ccount").
		Joins("left join user on user.id=post.user_id").
		Limit(limit).Offset((page-1)*limit).
		Order("created_at desc").
		Find(&postUserList)

	return postUserList,count
}
//单个文章查询
func (this *PostShow)PostFind(postId int) ([]Comments) {

	var comments []Comments

	//文章内容
	wl.DB.Table("post").Select("post.*,user.username").
		Joins("left join user on user.id=post.user_id").
		Where("post.id=?",postId).
		First(&this)

	//评论列表
	wl.DB.Table("comment").Select("user.username,comment.*").
		Joins("left join user on user.id = comment.user_id").
		Where("post_id=?",postId).
		Order("created_at desc").
		Find(&comments)

	return comments
}


//添加文章
func (this *Post)CreatePost() {
	this.Isok="1"
	wl.DB.Create(&this)
}

//修改文章
func (this *Post)UpdatePost() int64 {

	//err:=wl.DB.Model(&this).Update("title","content").RowsAffected
	err:=wl.DB.Model(&this).Updates(map[string]interface{}{"title": this.Title,"content":this.Content}).RowsAffected

	return err
}
//删除文章
func (this *Post)DeletePost() int64{
	 return wl.DB.Delete(&this).RowsAffected
}




//评论结构
type Comments struct {
	Id   uint
	Username    string
	UserId  int
	PostId  int
	Content    string
	CreatedAt   string
	UpdatedAt string
}

//评论新增结构
type CommentInster struct {

	Id   uint
	UserId  int
	PostId  int
	Content    string
	BaseMode
}
//添加评论
func (this *CommentInster)CreateCommit() {

	wl.DB.Create(&this)

}
//
func (this *CommentInster)FindCommit() CommentInster  {
	var comment CommentInster
	wl.DB.First(&comment)
	return comment
}


//赞
type Zan struct {
	Id   int
	UserId   int
	PostId   int
	BaseMode
}

//查询是否赞
func (this *Zan)IsZan()   {

	wl.DB.Where("user_id = ? and post_id=?", this.UserId,this.PostId).Find(&this)

}
//添加赞
func (this *Zan)CreatedZan()   {

	wl.DB.Create(&this)

}

//取消赞
func (this *Zan)DeleteZan()  int64 {

	return wl.DB.Delete(&this).RowsAffected

}


func (u *Comments) TableName() string {
	return "comment"
}
func (u *CommentInster) TableName() string {
	return "comment"
}